$(function () {
  var earth = null;
  var zoomLevel = 3;
  var poetIndex = 0;
  var poemIndex = -1;
  var language = 0;
  var markers = {};

  initialize();
  reset();

  function initialize() {
    earth = new WE.map('earth-div');
    WE.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager_labels_under/{z}/{x}/{y}{r}.png').addTo(earth);

    var html = template('poet-cards', { list: chinesePoets });
    $('#poets').empty().append(html);
    $('#poets .poet .card-title .btn').click(function () {
      poetIndex = $(this).parents('.col').index();
      if ($(this).parents('.poet').hasClass('selected')) return;
      $('#poets .poet').removeClass('selected');
      $('#poets .poet .card-title .btn').removeClass('btn-outline-success').add('btn-outline-secondary');
      $(this).parents('.poet').addClass('selected');
      $(this).addClass('btn-outline-success');
      $('#introduction-tab li:first-child button').tab('show');
      showContent();
    });

    $('#reset-button').click(function () {
      $('input[name="language"]').eq(0).prop('checked', true);
      $('.language-group .btn').removeClass('active');
      $('.language-group .btn').eq(0).addClass('active');
      language = 0;
      reset();
      $('html').animate({ scrollTop: 0 }, 800);
    });

    $('#experience').on('click', 'table tbody tr', function () {
      var $row = $(this);
      var key = $row.data('location-key');
      $('#experience table tbody tr').removeClass('selected');
      $row.addClass('selected');
      earth.panTo([locations[key].latitude, locations[key].longitude], { duration: 1 });
      var timeoutId = setTimeout(function () {
        clearTimeout(timeoutId);
        for (var k in markers) {
          if (k === key) {
            closePopups();
            markers[key].openPopup();
            showMarkerPopup(key, $row.index(), true);
            break;
          }
        }
      }, 2100);
    });

    $('#representative-poems input[name="language"]').on('change', function () {
      language = $('input[name="language"]').eq(0).prop('checked') ? 0 : 1;
      changeLanguage();
    });

    $('#representative-poems .catalog-col').on('click', '.list-group-item', function () {
      selectPoem($(this).index());
    });

    $('#earth-div .btn-group .btn').click(function () {
      [zoomIn, zoomOut][$(this).index()]();
    });

    $('#earth-div').on('click', function (e) {
      var $target = $(e.target);
      if (e.target.tagName === 'CANVAS' || $target.hasClass('we-pp-close')) {
        closePopups();
      } else if ($target.parents('.we-pm-icon').length) {
        var key = $target.parents('.we-pm-icon').find('.location-marker').data('key');
        closePopups(key);
        if ($('#experience table tbody tr.selected').data('location-key') !== key) {
          var index = showMarkerPopup(key, -1, true);
          scrollExperienceTable(index);
        }
      } else if ($target.hasClass('btn') && $target.parents('.experience-popup').length) {
        var key = $target.parents('.experience-popup').data('key');
        var index = showMarkerPopup(key, $target.hasClass('next') ? -3 : -2, true);
        scrollExperienceTable(index);
      }
    });

    $(document).keyup(function (e) {
      if (e.keyCode === 27) {
        closePopups();
      }
    });
  }

  function zoomIn() {
    zoomLevel = earth.getZoom() + 0.5;
    earth.setZoom(zoomLevel);
  }

  function zoomOut() {
    zoomLevel = earth.getZoom() - 0.5;
    if (zoomLevel <= 0) return;
    earth.setZoom(zoomLevel);
  }

  function reset() {
    poetIndex = 0;
    $('#poets .poet').removeClass('selected');
    $('#poets .poet .card-title .btn').removeClass('btn-outline-success').add('btn-outline-secondary');
    $('#poets .row .col').eq(0).find('.poet').addClass('selected');
    $('#poets .row .col').eq(0).find('.poet .btn').addClass('btn-outline-success');
    $('#introduction-tab li:first-child button').tab('show');
    showContent();

    zoomLevel = 3;
    earth.setView([locations['Beijing'].latitude, locations['Beijing'].longitude], zoomLevel);
    closePopups();
    createMarkers();
  }

  function createMarkers() {
    $.each(markers, function (index, marker) {
      earth.removeMarker(marker);
    });
    markers = {};
    var locationKeys = [];
    $.each(chinesePoets[poetIndex].experience, function (index, item) {
      var key = item.location;
      if (item.location in locations && locationKeys.indexOf(key) < 0) {
        var marker = WE.marker([locations[key].latitude, locations[key].longitude]).addTo(earth);
        var experiences = getExperiencesByLocation(key);
        var $popup = $('<div class="experience-popup"></div>');
        var $p = $('<p></p>');
        var $content = $('<div class="content"></div>');
        $p.text(locations[key].country ? (locations[key].country) + ' (' + locations[key].name + ')' : locations[key].name);
        $popup.append($p);
        $.each(experiences, function (index, item) {
          var $div = $('<div></div>');
          $div.attr('data-index', item.index);
          $div.append('<p></p>');
          $div.find('p:last-child').text(item.data.when);
          $div.append('<p></p>');
          $div.find('p:last-child').text(item.data.prompt);
          $content.append($div);
        });
        $popup.append($content);
        if (experiences.length > 1) {
          $popup.append('<div class="text-right"><div class="btn-group">' +
            '<button type="button" class="btn btn-light btn-sm previous">Previous</button>' +
            '<button type="button" class="btn btn-light btn-sm next">Next</button>' +
            '</div></div>');
        }
        $popup.attr('data-key', key);
        marker.bindPopup($popup[0].outerHTML, { maxWidth: 240, closeButton: true });
        showMarkerPopup(key, -1, false);
        locationKeys.push(key);
        markers[key] = marker;
      }
    });
    $('.we-pm-icon').each(function (index) {
      $(this).append('<svg id="marker' + index + '" class="location-marker" height="30" width="30" data-key="' + locationKeys[index] + '"">' +
        '<circle cx="15" cy="15" r="7.5" fill="#C91F25" opacity="0.75" /></svg>');
    });
  }

  function getExperiencesByLocation(where) {
    var experiences = [];
    $.each(chinesePoets[poetIndex].experience, function (index, item) {
      if (item.location === where) {
        experiences.push({ index: index, data: item });
      }
    });
    return experiences;
  }

  function closePopups(openKey) {
    if (!openKey) {
      $('#experience table tbody tr').removeClass('selected');
    }
    for (var key in markers) {
      var marker = markers[key];
      if (!openKey || openKey !== key) {
        marker.closePopup();
      }
    }
  }

  function showContent() {
    var data = chinesePoets[poetIndex];
    var html;
    var list;

    html = template('introduction-text', {
      name: data.name,
      chineseName: data.chineseName,
      list: data.introduction
    });
    $('#introduction').empty().append(html);

    $('#experience').find('h3 span').text(data.name);
    $('#publishing-works').find('h3 span').text(data.name);
    $('#representative-poems').find('h3 span').text(data.name);

    html = template('experience-table', { list: data.experience, locations: locations });
    $('#experience .table-responsive').empty().append(html);

    html = template('publishing-works-table', { list: formatPublishingWorks(data.publishingWorks) });
    $('#publishing-works .table').remove();
    $('#publishing-works').append(html);

    list = data.representativePoems.en;
    html = template('representative-poems-catalog', { list: list });
    $('#representative-poems .catalog-col').empty().append(html);
    poemIndex = -1;
    if (list.length) {
      selectPoem(0);
    } else {
      selectPoem(-1);
    }

    if (data.experience.length) {
      var location = locations[data.experience[0].location];
      earth.setView([location.latitude, location.longitude], zoomLevel);
    }

    closePopups();
    createMarkers();
  }

  function showMarkerPopup(key, index, select) {
    var $content = $('.experience-popup[data-key="' + key + '"] .content');
    var $buttonGroup = $content.parents('.experience-popup').find('.btn-group');
    var count = $content.find('div').length;
    var currentIndex = 0;
    $.each($content.find('div'), function (index, item) {
      if (!$(item).is(':hidden')) currentIndex = index;
    });
    $content.find('div').hide();
    if (index === -1) {
      currentIndex = count - 1;
      index = $content.find('div:last-child').data('index');
    } else if (index < 0) {
      if (index === -3) {
        currentIndex = Math.min(currentIndex + 1, count - 1);
      } else {
        currentIndex = Math.max(currentIndex - 1, 0);
      }
      index = $($content.find('div').eq(currentIndex)).data('index');
    } else {
      $.each($content.find('div'), function (i, item) {
        if ($(item).data('index') === index) currentIndex = i;
      });
    }
    $content.find('div[data-index="' + index + '"').show();
    $buttonGroup.find('.previous').prop('disabled', currentIndex === 0);
    $buttonGroup.find('.next').prop('disabled', currentIndex === count - 1);
    if (select) {
      $('#experience table tbody tr').removeClass('selected');
      $($('#experience table tbody tr').eq(index)).addClass('selected');
    }
    return index;
  }

  function scrollExperienceTable(index) {
    if (index >= 0) {
      var $row = $('#experience table tbody tr').eq(index);
      var top = $row.position().top;
      $('#experience .row .col').eq(0).animate({ scrollTop: top }, 300);
    }
  }

  function changeLanguage() {
    var data = chinesePoets[poetIndex];
    var html = template('representative-poems-catalog', { list: data.representativePoems.en });
    $('#representative-poems .catalog-col').empty().append(html);
    selectPoem(poemIndex);
  }

  function selectPoem(index) {
    var data = chinesePoets[poetIndex];
    var list = language === 1 ? data.representativePoems.zh : data.representativePoems.en;
    var html;
    poemIndex = index;
    $('#representative-poems .catalog-group .list-group-item').removeClass('active');
    if (index < 0) {
      $('#representative-poems .content-col').empty();
    } else {
      $('#representative-poems .catalog-group .list-group-item').eq(index).addClass('active');
      html = template('representative-poems-content', { data: list[index] });
      $('#representative-poems .content-col').empty().append(html);
    }
    $('#representative-poems .content-box').addClass(language === 1 ? 'zh' : 'en');
  }

  function formatPublishingWorks(items) {
    var list = [];
    var types = {};
    var type = '';
    $.each(items, function (index, item) {
      if (item.type in types) {
        types[item.type] += 1;
      } else {
        types[item.type] = 1;
      }
    });
    $.each(items, function (index, item) {
      if (item.type !== type) {
        type = item.type;
        list.push({
          rowspan: types[type],
          type: item.type,
          works: item.works,
          time: item.time,
        });
      } else {
        list.push({
          works: item.works,
          time: item.time,
        });
      }
    });
    return list;
  }
});
